package com.platform.generate.core.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.db.DbUtil;
import cn.hutool.db.Entity;
import cn.hutool.db.handler.EntityListHandler;
import cn.hutool.db.sql.SqlExecutor;
import cn.hutool.log.Log;
import com.google.common.collect.Lists;
import com.platform.generate.modular.result.InformationResult;
import com.platform.core.exception.ServiceException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据源链接工具类
 *
 */
public class TablesUtil {

    private static final Log log = Log.get();

    private static final String DATA_SOURCE_SQL = " select table_name,create_time,update_time,table_comment from information_schema.tables where table_schema = ?";

    private static final String TABLE_NAME = "table_name";

    private static final String CREATE_TIME = "create_time";

    private static final String UPDATE_TIME = "update_time";

    private static final String TABLE_COMMENT = "table_comment";


    public static List<InformationResult> informations(String url, String account, String password) {

        Connection conn = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 获取数据库连接配置
            String dataSourceUrlCurrent = url;
            String dataSourceUsernameCurrent = account;
            String dataSourcePasswordCurrent = password;

            String dataBaseName = Util.getDataBasename(url,"mysql");
            conn = DriverManager.getConnection(dataSourceUrlCurrent, dataSourceUsernameCurrent, dataSourcePasswordCurrent);

            List<Entity> dataSourceEntity = SqlExecutor.query(conn, DATA_SOURCE_SQL, new EntityListHandler(),dataBaseName);
            List<InformationResult> results = Lists.newArrayList();
            for(Entity entity : dataSourceEntity){
                InformationResult informationResult = new InformationResult();
                informationResult.setTableName(entity.get(TABLE_NAME).toString());
                informationResult.setCreateTime(entity.get(CREATE_TIME).toString());
                informationResult.setUpdateTime(ObjectUtil.isNull(entity.get(UPDATE_TIME))?"":entity.get(UPDATE_TIME).toString());
                informationResult.setTableComment(entity.get(TABLE_COMMENT).toString());
                results.add(informationResult);
            }
            return results;

        } catch (SQLException | ClassNotFoundException e) {
            log.error(">>> 读取数据库constants配置信息出错：");
            e.printStackTrace();
            throw new ServiceException(1,"数据库连接失败，请检查用户名密码是否正确。");
        } finally {
            DbUtil.close(conn);
        }

    }
}
